//
//  HZPicsCarouselView.m
//  app
//
//  Created by 刘华舟 on 15/5/26.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZPicsCarouselView.h"
#import "UIImageView+URL.h"

#define _DEFAULT_INTERVAL 5.0

@interface HZPicsCarouselView()<UIScrollViewDelegate>
{
    UIScrollView* _scroller;
    UIPageControl* _pageCtrl;
    NSTimer* _myTimer;
}

@property (strong, nonatomic) NSArray* data;

@end


@implementation HZPicsCarouselView

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.contentMode = UIViewContentModeRedraw;
        
        self.backgroundColor = [UIColor whiteColor];
        _scroller = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scroller.pagingEnabled = YES;
        _scroller.delegate = self;
        _scroller.showsHorizontalScrollIndicator = NO;
        _scroller.showsVerticalScrollIndicator = NO;
        _scroller.bounces = NO;
        [self addSubview:_scroller];
        
        _pageCtrl = [[UIPageControl alloc] initWithFrame:CGRectOf([self.ufo fx:UB_1_4 fy:UB_5_6],
                                                                  [self.ubo fw:UB_HALF fh:UB_1_5])];
        _pageCtrl.backgroundColor = HZ_CLEAR_COLOR;
        
        _pageCtrl.pageIndicatorTintColor = HZ_WHITE_COLOR;
        _pageCtrl.currentPageIndicatorTintColor = HZ_FORUM_THEME_GREEN_COLOR;
        
        //[self setPageControlAlignment:JKAdPageControlAlignmentCenter];
        [self addSubview:_pageCtrl];
        
    }
    return self;
}

-(NSInteger)pageCount
{
    return _pageCtrl.numberOfPages;
}

-(NSInteger)currentPage{
    return _pageCtrl.currentPage;
}

- (void)setCurrentPage:(NSInteger)currentPage
{
    _scroller.contentOffset = CGPointMake(CGRectGetWidth(_scroller.bounds) * currentPage, 0);
    _pageCtrl.currentPage = currentPage;
}

-(void)didImageTap:(UITapGestureRecognizer*)sender
{
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        if (self.pageTappedCaller) {
            NSDictionary *dict = @{@"array":self.data,
                                   @"index":[NSNumber numberWithInteger:_pageCtrl.currentPage],
                                   @"urlKey":APIKEY_mall_pic};
            [self.pageTappedCaller call:dict];
        }
    }
}

-(void)showPages:(NSArray*)array
        imageKey:(NSString*)imageKey
        titleKey:(NSString*)titleKey
{
    [_myTimer invalidate];
    _scroller.frame = self.bounds;
    _pageCtrl.frame = CGRectOf([self.ufo fx:UB_1_4 fy:UB_5_6],
                                                              [self.ubo fw:UB_HALF fh:UB_1_5]);
    self.data = array;
    CGSize contentSize = _scroller.bounds.size;
    contentSize.width = _scroller.bounds.size.width * [array count];
    _scroller.contentSize = contentSize;
    for (int i=0; i < [array count]; i++) {
        NSDictionary* data = [array valueAtIndex:i];
        
        CGRect imgFrame = _scroller.bounds;
        imgFrame.origin.x = imgFrame.size.width * i;
        UIImageView* imgView = [[UIImageView alloc] initWithFrame:imgFrame];
        imgView.backgroundColor = HZ_FORUM_LIGHTGRAY_BACKGROUND_COLOR;
        //[imgView setImageWithURL:[data stringForKey:imageKey]];
        //图像的动画特效
        [imgView sd_setImageWithURL:[NSURL URLWithString:[data stringForKey:imageKey]] placeholderImage:nil options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (cacheType == SDImageCacheTypeNone){
                imgView.alpha = 0.0f;
                [UIView animateWithDuration:0.2f animations:^{
                    imgView.alpha = 1.0f;
                }];
            }
        }];
        imgView.contentMode = UIViewContentModeScaleToFill;
        [_scroller addSubview:imgView];
        imgView.userInteractionEnabled = YES;
        UITapGestureRecognizer* recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didImageTap:)];
        [imgView addGestureRecognizer:recognizer];
        
    }
    _pageCtrl.numberOfPages = [array count];
    _pageCtrl.currentPage = 0;
    
    _myTimer = [NSTimer scheduledTimerWithTimeInterval:_DEFAULT_INTERVAL target:self selector:@selector(scrollToNextPage) userInfo:nil repeats:YES];
    
    if (array.count>1) {
        _pageCtrl.hidden = NO;
    }else{
        _pageCtrl.hidden = YES;
    }
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetX = scrollView.contentOffset.x;
    CGFloat pageWidth = CGRectGetWidth(scrollView.bounds);
    NSUInteger page = floor((offsetX + pageWidth/2.0) / pageWidth);
    _pageCtrl.currentPage = page;
}

- (void)scrollToNextPage{
    NSInteger nextPage = (_pageCtrl.currentPage + 1)%4;
    _pageCtrl.currentPage = nextPage;
    
    
    int pageNum = _pageCtrl.currentPage;
    CGSize viewSize= _scroller.frame.size;
    CGRect rect=CGRectMake((pageNum)*viewSize.width, 0, viewSize.width, viewSize.height);
    [_scroller scrollRectToVisible:rect animated:YES];
    
}

- (void)dealloc{
    [_myTimer invalidate];
}


@end
